package violentRecursion;

import org.junit.Test;

/**
 * @author kunkun
 * @className LeetCode_416
 * @Description ...
 * @date 2025/3/17 16:56
 */
public class LeetCode_416 {

    public boolean canPartition(int[] nums) {
        int sum = 0;
        for (int num : nums) {
            sum+=num;
        }
        if (sum%2!=0){
            return false;
        }
//        return solution_1(nums,sum/2,0);
        return solution_2(nums,sum/2,0);
    }

    @Test
    public void test(){
        System.out.println(canPartition(new int[]{1, 5, 11, 5}));
    }

    //递归实现
    private boolean solution_1(int[] nums,int sum, int index) {
        if (index>=nums.length){
            return false;
        }
        if (sum==0){
            return true;
        }
        if (sum<0){
            return false;
        }
        return solution_1(nums,sum,index+1)||solution_1(nums,sum-nums[index],index+1);

    }

    //动态规划
    private boolean solution_2(int[] nums,int sum, int index) {
        //1. 定义初始变量
        Boolean[][] res = new Boolean[nums.length+1][sum+1];
        for (int i = 0; i < res.length; i++) {
            res[i][0]= true;
            if (i==nums.length){
                for (int j = 0; j < sum+1; j++) {
                    res[i][j]= false;
                }
            }
        }
        //2. 设置值
        for (int i = nums.length-1; i >= 0 ; i--) {
            for (int j = 1; j < sum+1; j++) {
                if (j-nums[i]>=0){
                    res[i][j] = res[i+1][j] || res[i+1][j-nums[i]];
                }else{
                    res[i][j] = res[i+1][j];
                }
            }
        }
        return res[0][sum];


    }

}
